package com.test.handler;


import com.test.code.IErrorCode;
import com.test.expection.MyException;
import com.test.vo.ResponseResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionControllerAdvice {
    @ExceptionHandler(MyException.class)
    public ResponseResult handleMyException(MyException exception) {
        IErrorCode errorCode = exception.getErrorCode();
        ResponseResult responseResult = ResponseResult.failure(errorCode.getCode(), errorCode.getErrorMsg());
        return responseResult;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidationExceptions(MethodArgumentNotValidException ex) {
        StringBuilder errorMessage = new StringBuilder();

        // 使用 BindingResult 获取所有错误信息
        BindingResult bindingResult = ex.getBindingResult();
        bindingResult.getAllErrors().forEach((error) -> {
            // 检查错误类型并处理
            if (error instanceof FieldError) {
                String fieldName = ((FieldError) error).getField();
                String errorText = error.getDefaultMessage();
                errorMessage.append(fieldName).append(": ").append(errorText).append("; ");
            } else {
                // 处理非 FieldError 类型的错误
                errorMessage.append(error.getObjectName()).append(": ").append(error.getDefaultMessage()).append("; ");
            }
        });

        // 移除最后一个多余的分号和空格
        if (errorMessage.length() > 0) {
            errorMessage.setLength(errorMessage.length() - 2);
        }

        return ResponseResult.failure(errorMessage.toString());
    }
}